package com.xsz.pda.api

import android.util.Log
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.TypeReference
import com.blankj.utilcode.util.LogUtils
import com.github.kittinunf.fuel.core.extensions.jsonBody
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.fuel.httpPost
import com.github.kittinunf.result.Result
import com.xsz.pda.api.beans.*
import com.xsz.pda.net.Constant

class TicketServiceApi(ip:String) {
    private val TAG = "TicketServiceApi"
    private val serverPort = Constant.CONTROL_SERVER_PORT
    private val baseUrl = "http://$ip:$serverPort"
    private val timeout = 3000
    private val URL_GETPROJECTNAME = "/checker/api/client/getProjectName"
    private val URL_INIT_DATA = "/checker/api/client/initData"
    private val URL_SYNC_DATA = "/checker/api/client/syncData"
    private val URL_GET_ALL_TYPE_GROUP = "/checker/api/client/sys/checkBase"
    private val URL_UPLOAD_PICTURE = "/checker/api/client/uploadPicture"
    private val URL_UPLOAD_FACE = "/checker/api/client/uploadFace"
    private val URL_DOWNLOAD_PICTURE = "/sys/common/static/"

    //下载局域网服务器
    private val URL_DOWNLOAD_WLAN_PICTURE = "/downloadPicture"

    fun initData(lastSyncId: String, projectId: String, androidId: String): ApiInitTicket? {
        val (_, _, result) = "$baseUrl$URL_INIT_DATA"
            .httpGet(listOf("lastSyncId" to lastSyncId, "projectId" to projectId,"androidId" to androidId))
            .timeout(timeout = timeout)
            .responseString()
        return when(result){
            is Result.Failure-> {
                Log.e(TAG, "初始化数据时，网络异常... ${result.error}")
                null
            }
            is Result.Success->{
                val apiResult = JSON.parseObject<ApiResult<ApiInitTicket>>(result.value, object :
                    TypeReference<ApiResult<ApiInitTicket>>(){}.type)
                if (apiResult.isSuccess) {
                    apiResult.result.timestamp = apiResult.timestamp
                   apiResult.result
                } else {
                    Log.e(TAG, apiResult.message)
                    null
                }
            }
        }
    }

    fun syncData(lastSyncTime: Long,
                 lastSyncRecordTime: Long,
                 lastItemTime: Long,
                 projectId: String,
                 maxId: String,
                 name: String,
                 lastSyncFaceTime: Long,
                 firstCheck: String, ): ApiSyncTicket? {
        val (_, _, result) = "$baseUrl$URL_SYNC_DATA"
            .httpGet(listOf(
                "lastSyncTime" to lastSyncTime,
                "lastItemTime" to lastItemTime,
                "firstCheck" to firstCheck,
                "syncRecord" to false,
                "lastSyncRecordTime" to lastSyncRecordTime,
                "projectId" to projectId,
                "name" to name,
                "maxId" to maxId,
                "lastSyncFaceTime" to lastSyncFaceTime
            ))
            .timeout(timeout = 1500)
            .responseString()
        return when(result){
            is Result.Failure-> {
                Log.d(TAG, "同步数据时,网络异常${result.error.message}")
                null
            }
            is Result.Success->{
                val apiResult = JSON.parseObject<ApiResult<ApiSyncTicket>>(result.value, object :
                    TypeReference<ApiResult<ApiSyncTicket>>(){}.type)
                if (apiResult.isSuccess) {
                    apiResult.result
                } else {
                    LogUtils.w(apiResult.message)
                    null
                }
            }
        }
    }

    fun syncData(records: List<ApiCheckRecord>): Boolean {
        val (_, _, result) = "$baseUrl$URL_SYNC_DATA"
            .httpPost()
            .jsonBody(JSON.toJSONString(records))
            .timeout(timeout = 2000)
            .responseString()
        return when(result){
            is Result.Failure-> {
                Log.e(TAG, "同步数据失败，网络异常... ${result.error}")
                false
            }
            is Result.Success->{
                JSON.parseObject<ApiResult<String>>(
                    result.value, object:TypeReference<ApiResult<String>>() {}.type
                ).isSuccess
            }
        }
    }

    fun getCheckBase(androidId: String):  ApiCheckBase? {
        val (_, _, result) = "$baseUrl$URL_GET_ALL_TYPE_GROUP"
            .httpGet(listOf("androidId" to androidId))
            .timeout(timeout = 2000)
            .responseString()
        return when(result){
            is Result.Failure-> {
                Log.e(TAG, "获取设设备组票型信息失败... ${result.error}")
                null
            }
            is Result.Success->{
                JSON.parseObject<ApiResult<ApiCheckBase>>(
                    result.value, object:TypeReference<ApiResult<ApiCheckBase>>() {}.type
                ).result
            }
        }
    }
    fun register(
        androidId: String,
        suc: (String) -> Unit,
        fail: (String) -> Unit
    ) {
        "$baseUrl${Constant.CONTROL_URL_REGISTER}"
            .httpPost(listOf("androidId" to androidId))
            .timeout(timeout = 2000)
            .responseString { _, _, rlt ->
                rlt.fold(
                    {
                        val apiResult =JSON.parseObject<ApiResult<String>>(it, object :TypeReference<ApiResult<String>>(){}.type)
                        if (apiResult.isSuccess) {
                            suc(apiResult.message)
                        } else {
                            fail(apiResult.message)
                        }
                    },
                    { fail("无法连接服务器") })
            }
    }

    fun getAllGroups(
        suc: (List<DeviceGroup>) -> Unit,
        fail: (String) -> Unit
    ) {
        "$baseUrl${Constant.GET_ALL_GROUPS}"
            .httpGet()
            .timeout(timeout = 2000)
            .responseString { _, _, rlt ->
                rlt.fold(
                    {
                        val apiResult:ApiResult<List<DeviceGroup>> =JSON.parseObject(it, object :TypeReference<ApiResult<List<DeviceGroup>>>(){}.type)
                        if (apiResult.isSuccess) {
                            suc(apiResult.result)
                        } else {
                            fail(apiResult.message)
                        }
                    },
                    { fail("无法连接服务器") })
            }
    }
}